import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCounterStore = defineStore('counter', () => {
  // 状态
  const count = ref(0)

  // 计算属性
  const doubleCount = computed(() => count.value * 2)
  const isEven = computed(() => count.value % 2 === 0)

  // 方法
  function increment() {
    count.value++
  }

  function decrement() {
    count.value--
  }

  function reset() {
    count.value = 0
  }

  function setCount(value: number) {
    count.value = value
  }

  function initCounter() {
    // 持久化插件会自动恢复状态，无需手动操作
  }

  // 监听状态变化，自动保存到 localStorage (现在由持久化插件自动处理)
  function saveToStorage() {
    // 持久化插件会自动处理，这个方法保留用于兼容性
  }

  return {
    count,
    doubleCount,
    isEven,
    increment,
    decrement,
    reset,
    setCount,
    initCounter,
    saveToStorage
  }
}, {
  persist: {
    key: 'counter-store',
    storage: localStorage,
    pick: ['count'] // 持久化计数值
  }
})